import { Button, Card, Col, List, Layout, Icon, Row, Select, Form, Modal } from 'antd';
import { MenuUnfoldOutlined,MenuFoldOutlined } from '@ant-design/icons';
import React, { Component } from 'react';
import style from './style.less';
import ProjectInfoForm from '@/pages/project/components/ProjectInfoForm';
import FileForm from '../components/FileForm';
import DataInfoForm from './DataInfoForm';
import ModularInfoForm from './ModularInfoForm';
import MicroFrom from './MicroFrom';
import { detailEntityApi as getProjectApi } from '../manager/service';
import { queryList } from './services/modularInfo';
import $ from './jquery-vendor'
import Qs from 'qs';
import ztree from 'ztree';
import { connect } from 'dva';
import 'ztree/css/zTreeStyle/zTreeStyle.css';
import { Config } from '../../../utils/constants';

const { Option } = Select;
const { Header, Sider, Content } = Layout;

const entityNameSpace = 'project';

@connect(({ project, loading }) => ({
  project,
  loading: loading.models.project,
}))
class ProjectConfig extends Component {

  ztreeIndex = 0;
  ProjectInfoForm;
  DataInfoForm;
  ModularInfoForm;
  MicroFrom;
  rightClickNode;
  openStats = {};
  fileFormRef;
  fileTree = null;
  packageType = 'Hierarchical';
  moduleId = '0';


  state = {
    collapsed: false,
    projectDetail: {},
    modularList: [],
    rightMenu: {
      left: '0px',
      top: '0px',
      display: 'none'
    },
    rightClickMicroId: 0,
    projectTree: [], // 树
  };

  componentDidMount() {

    this.fetchProjectInfo();
    this.fetchProjectFileTree()
    let that = this;
    $(document)
      .bind('click', function (e) {
        that.setState({
          ...that.state,
          rightMenu: { display: 'none' }
        })
      });

  }

  fetchProjectFileTree = () => {
    const { dispatch } = this.props;
    let projectId = window.location.href.split('?')[1].split('=')[1];

    let params = {
      projectId: projectId,
      packageType: this.packageType,
      moduleId: this.moduleId
    }

    dispatch({
      type: `${entityNameSpace}/queryEntityPageList`,
      payload: params,
      callback: res => this.setState({ projectTree: eval(res.data) })
    });
  };


  fetchProjectInfo = () => {
    let projectId = window.location.href.split('?')[1].split('=')[1];
    getProjectApi(projectId)
      .then(res => {
        this.setState({ projectDetail: res.data });
      });
    queryList({ projectId: projectId })
      .then(res => {
        this.setState({ modularList: res.data })
      })
  };


  showAddFilePanel = () => {
    this.setState({
      ...this.state,
      rightMenu: { display: 'none' }
    })

    this.fileFormRef.showFileFormPanel({ fileType: this.rightClickNode.name }, (ret) => {
      if (ret == 'add' || ret == 'update') {
        // reload
        this.fetchProjectFileTree();
      }
    })
  };

  addTab = (treeNode) => {

    const tabPanes = this.state.tabPanes;
    const activeKey = 'panel_' + treeNode.id;
    var noOpen = true;
    for (var i = 0; i < tabPanes.length; i++) {
      if (treeNode.id === tabPanes[i].id) {
        noOpen = false;
        break;
      }
    }
    if (noOpen) {
      tabPanes.push(treeNode);
      this.setState({
        ...this.state,
        tabPanes,
        activeKey
      });
    }
  }

  removeSelectedFile = () => {

    // 判断不可删除文件
    if ('vo' == this.rightClickNode.fileType) {
      console.log(Config)
      let ret = Config.VO_IGNORE.findIndex((element) => (element == this.rightClickNode.name.split('.')[0]))
      if (ret > -1) {
        Modal.error({
          title: '错误提示',
          content: '非自定义创建无法删除！',
        });
        return;
      }
    }

    var that = this;
    Modal.confirm({
      title: `是否删除【${this.rightClickNode.name}】文件?`,
      content: '请确认',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        var newTreeData = [];
        for (let i = 0; i < that.state.projectTree.length; i++) {
          if (that.state.projectTree[i].id != that.rightClickNode.id) {
            newTreeData.push(that.state.projectTree[i]);
          }
        }
        that.setState({
          ...that.state,
          projectTree: newTreeData
        })
        that.delFileInfoApi(that.rightClickNode.fileId)
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };

  delFileInfoApi = (fileId) => {
    const { dispatch } = this.props;

    dispatch({
      type: `${entityNameSpace}/removeEntity`,
      payload: { fileId: fileId },
      callback: res => {
        if (res.code === 10000) {
          this.fetchProjectFileTree()
        }
      }
    });
  }

  toggle = () => {
    this.setState({
      collapsed: !this.state.collapsed,
    });
  };

  render() {
    const { projectDetail, modularList, rightClickMicroId } = this.state;
    const { [entityNameSpace]: { projectTree } } = this.props;
    let projectId = window.location.href.split('?')[1].split('=')[1];

    let zNodes = projectTree;
    window.zNodes = zNodes;

    for (let i = 0; i < zNodes.length; i++) {

      let node = zNodes[i];
      let type = node.fileType;
      if (type === 'package') {
        node['icon'] = require('../../static/images/package_obj.gif');
      } else if (type === 'folder') {
        node['icon'] = require('../../static/images/source-folder.gif');
      } else {
        node['icon'] = require('../../static/images/jcu_obj.gif');
      }

      // open status
      if (this.openStats[node.indentify]) {
        node.open = true;
      } else if (this.openStats[node.indentify] === false) {
        node.open = false;
      }

      zNodes[i] = node;
    }

    let setting = {
      data: {
        simpleData: {
          enable: true
        }
      },
      callback: {
        onExpand: (event, treeId, treeNode) => {
          // console.info('onExpand---' + JSON.stringify(this.openStats));
          this.openStats[treeNode.indentify] = true;

          this.setState({ ...this.state });
        },
        onCollapse: (event, treeId, treeNode) => {

          // console.info('onCollapse---' + JSON.stringify(this.openStats));
          this.openStats[treeNode.indentify] = false;

          this.setState({ ...this.state });
        },
        onClick: (event, treeId, treeNode) => {

          if (treeNode.fileType === 'package') {
            this.openStats[treeNode.indentify] = true;
          } else {
            if (treeNode.getParentNode()) {
              this.openStats[treeNode.getParentNode().indentify] = true;
              this.addTab(treeNode);
            }
          }
          this.setState({ ...this.state });
        },
        onRightClick: (event, treeId, treeNode) => { // 右键事件
          // console.info('right click ' + JSON.stringify(treeNode));

          if (treeNode) {
            //if(treeNode.fileType === 'package')
            {
              this.rightClickNode = treeNode;
              this.setState({
                ...this.state,
                rightClickMicroId: treeNode.microId,
                rightMenu: {
                  display: '',
                  left: event.clientX + 'px',
                  top: (event.clientY - 60) + 'px'
                }
              })
            }
          }
        }
      }
    };

    this.fileTree = $.fn.zTree.init($(this.refs.ztree), setting, zNodes);
    document.title = projectDetail.name;

    return (
      <Layout>
        <Sider trigger={null} collapsible collapsed={this.state.collapsed} width='300px'>
          <div className={style.logo}>{projectDetail.name}</div>
          <div style={{
            background: 'white',
            overflow: 'auto',
            height: '100%',
            position: 'relative'
          }}>

            <div className="ztree" ref="ztree" id={`ztree_${this.ztreeIndex++}`}></div>

            <div className="right-menu-panel"
                 style={{
                   padding: '10px',
                   width: '240px',
                   position: 'absolute', ...this.state.rightMenu
                 }}>
              <List
                style={{ backgroundColor: 'white' }}
                size="small"
                bordered
              >
                <List.Item><a onClick={this.showAddFilePanel}><Icon
                  type="plus-circle"/>添加文件</a></List.Item>
                <List.Item><a onClick={this.removeSelectedFile}><Icon
                  type="close-circle"/>删除文件</a></List.Item>
              </List>
            </div>

          </div>
        </Sider>
        <Layout className={style.siteLayout}>
          <Header style={{
            padding: 0,
            background: '#fff'
          }}>
            <Row>
              <Col span={1}>
                {React.createElement(this.state.collapsed ? MenuUnfoldOutlined : MenuFoldOutlined, {
                  className: `${style.trigger}`,
                  onClick: this.toggle,
                })}
              </Col>
              <Col span={3}>
                <Select placeholder='Hierachical' style={{ width: '100%' }} onChange={(value) => {
                  this.packageType = value;
                  this.fetchProjectFileTree()
                }}>
                  <Option value='Flat'>Flat</Option>
                  <Option value='Hierachical'>Hierachical</Option>
                </Select>
              </Col>
              <Col span={3}>
                <Select placeholder='选择模块' style={{ width: '100%' }} onChange={(value) => {
                  this.moduleId = value;
                  this.fetchProjectFileTree()
                }}>
                  {modularList.map(v => (
                    <Option value={v.id}>{v.name}</Option>
                  ))}
                  <Option value="-1">--公共模块</Option>
                  <Option value="0">--显示全部</Option>
                </Select>
              </Col>
              <Col span={2}>
                <Button style={{ width: '100%' }}
                        onClick={() => this.ModularInfoForm.handleModalVisible(true, this.handleReloadTableList, projectId)}>模块管理</Button>
                <ModularInfoForm
                  projectId={projectId}
                  proType={projectDetail.proType}
                  onRef={ele => {
                    this.ModularInfoForm = ele;
                  }}/>
              </Col>
              <Col span={2}>
                <Button style={{ width: '100%' }}
                        onClick={() => this.ProjectInfoForm.handleModalVisible(true, this.handleReloadTableList, projectId)}>项目详情</Button>
                <ProjectInfoForm
                  onRef={ele => {
                    this.ProjectInfoForm = ele;
                  }}
                />
              </Col>
              <Col span={2}>
                <Button style={{ width: '100%' }}
                        onClick={() => this.DataInfoForm.handleModalVisible(true, this.handleReloadTableList, projectId)}>数据库表配置</Button>
                <DataInfoForm
                  projectId={projectId}
                  onRef={ele => {
                    this.DataInfoForm = ele;
                  }}/>
              </Col>
              {projectDetail.proType === 'micro' ?
                <Col span={2}>
                  <Button style={{ width: '100%' }}
                          onClick={() => this.MicroFrom.handleModalVisible(true, this.handleReloadTableList, projectId)}>添加微服务</Button>
                  <MicroFrom
                    projectId={projectId}
                    projectInfo={projectDetail}
                    onRef={ele => {
                      this.MicroFrom = ele;
                    }}/>
                </Col> : ''}
            </Row>
          </Header>
          <Content
            className={style.siteLayoutBackground}
            style={{
              margin: '24px 16px',
              minHeight: `${window.innerHeight}px`
            }}
          >
            <Card>
              Content
            </Card>
          </Content>
        </Layout>
        {/* 添加文件弹出框 */}
        <FileForm
          key="k_fileForm"
          projectDetail={projectDetail}
          projectId={projectId}
          microId={rightClickMicroId}
          modularList={modularList}
          onRef={(ref) => {
            this.fileFormRef = ref
          }}></FileForm>
      </Layout>
    );
  }
}

export default Form.create()(ProjectConfig);
